<?php
/**
 * 融360|app流量对接
 */
namespace Home\Controller;


use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Common\Vendor\Hook\BaseHook;
use Home\Model\ConsumeHistoryModel;
use Home\Model\CreditVettingModel;
use Home\Model\FinishModel;
use Think\Controller;
use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Log; 
use Think\OpenapiClient;
use Common\Library\SendSMS;
use Think\Cache\Driver\Redis;

class RongController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        try {
            Request::parse();//校验请求|sign值等
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }
  /*
   * 融360|请求找钱花-
   * @1---将融360请求的数据流--转换成标准的json格式-
   * @2---解析成数组
   *
   * */
    public function  jsonToArray(){
        $strPost = file_get_contents('php://input');
        $pattern = '/\"{/';//:"{}"字符串
        $replacement = '{';//转换成json
        $strPost=preg_replace($pattern, $replacement, $strPost);
        $pattern = '/}\"/';
        $replacement = '}';
        $strPost=preg_replace($pattern, $replacement, $strPost);
        $pattern = '/，/';//中文状态
        $replacement = ',';//英文状态
        $strPost=preg_replace($pattern, $replacement, $strPost);
        return json_decode($strPost,true);//解析成数组
    }
    /*
     * 融360|请求找钱花-
     * @param json字符串--"example":{}"
     * @将业务数据biz_data-转换成标准的json格式
     * */
    public function  jsonToArray_($strPost){
        $pattern = '/\"{/';
        $replacement = '{';
        $strPost=preg_replace($pattern, $replacement, $strPost);
        $pattern = '/}\"/';
        $replacement = '}';
        $strPost=preg_replace($pattern, $replacement, $strPost);
        return $strPost;
    }
    /*
     * @通过第三方订单号映射本app-对应的用户id|订单id
     * @param order_id
     * @return array[]
     * */
    public  function  getAppIdsByOrder($orderId){
        //订单映射表
        return M('ThirdpartyConsumeHistory')->field('id,customer_id,third_customer_id,order_no,third_order_no,type')->where('third_order_no='.int($orderId))->find();
    }
/*|request Rong360|测试-接口
 *请求--融360提供的接口
 */
    public function  request_rong(){
        $arr_=[];//业务数据-数组
        $arr_['order']='245132241561415';
        $arr_['timer']='28';
        $sample= new OpenapiClient();
        $sample->setMethod('is.api.v3.order.notifypushaddinfo');
        $sample->setField("version", "1.0");
        $sample->setField("biz_data",json_encode($arr_));//设置业务参数|数据
        $sample->setField("format", "json");
        $sample->setField("sign_type", "RSA");
        $ret= $sample->execute();//向融360请求
        var_dump($ret);
         if($ret['code']==200){
             //请求成功
         }else{
            //请求失败
         }
    }
    /*|找钱花对外（融360）提供的接口|示例接口
     *
     * */
    public  function  accept_rong(){
        $postArray=$this->jsonToArray();//获取融360请求过来的数据流
        $data =  $postArray['biz_data']; //业务数据
        //$sign = $postArray['sign'];//融360的签名
        //业务逻辑处理
        if(1==1){
            $ret = [];
            $ret['status'] = '00';
            $ret['msg'] = 'msg';
            $ret['data'] = $data;
            $this->ajaxReturn($ret);//将结果|数据推送给融360
        }
    }
    /**********************|融360运营商报告推送|************************
     *荣荣推送的运营商报告
     *|小荣荣给的不是json|多了""|结束]时多了','|务必注意此坑
     *
     */
    public  function  mobileReportByRong(){
        $postArray=$this->jsonToArray();
         //print_r($postArray);
         //var_dump($postArray['biz_data']);
        //echo json_encode($postArray['biz_data']);//
        echo $postArray['biz_data']['order_no'];//订单号
        /***********************订单号|关联系统订单id|系统用户id*************************/
        $app_order=$this->getAppIdsByOrder($postArray['biz_data']['order_no']);
        if(!$app_order){
            $this->ajaxReturn(['code'=>'201',''=>'第三方订单号错误']);
        }
        //$app_user=$this->getAppIdsByOrder($postArray['biz_data']['order_no']);
        echo $postArray['biz_data']['download_url'];//下载地址
        //var_dump($postArray['biz_data']['head_info']);//报告头信息
        print_r($postArray['biz_data']['input_info']);//用户输入信息|紧急联系人
        //var_dump($postArray['biz_data']['input_info']);//用户输入信息
        //var_dump($postArray['biz_data']['basic_info']);//用户基本信息
        //var_dump($postArray['biz_data']['risk_analysis']);//危险性分析
        //var_dump($postArray['biz_data']['risk_analysis']);//危险性分析
        //var_dump($postArray['biz_data']['user_portrait']);//用户画像|通话记录分析
        /**********************机构录入用户extra信息**********************/
        $postArray['biz_data']['input_info']['emergency_name1'];//紧急联系人|暂时存入extra表
        $extra_data=[];
        $extra_data['frieds_name']=$postArray['biz_data']['input_info']['emergency_name1'];
        $extra_data['frieds_phone']=$postArray['biz_data']['input_info']['emergency_phone1'];
        $extra_data['colleague_name']=$postArray['biz_data']['input_info']['emergency_name2'];
        $extra_data['colleague_phone']=$postArray['biz_data']['input_info']['emergency_phone2'];
        $extra_data['customer_id']=$app_order['customer_id'];
        $extra_res=M('CustomerExtraInfo')->add($extra_data);
        //数据保存|
        $extra_data_all=json_encode($postArray['biz_data']);
        var_dump($extra_res);
        var_dump($extra_data_all);
        if($extra_res&$extra_data_all){

        }else{

        }

    }
    /***重推运营商报告接口(融360提供)***
     *---融360异步请求|推送运营商报告接口|
     * @param
     * @return
     ************************************/
    public  function reCompleteMobile(){
        $arr_ = [];//业务数据-数组
        $arr_['order_no'] = '245132241561415';
        $arr_['timer'] = '28';
        $sample = new OpenapiClient();
        $sample->setMethod('is.api.v3.order.notifypushmobilereport');
        $sample->setField("version", "1.0");
        $sample->setField("biz_data",json_encode($arr_));//设置业务参数|数据
        $sample->setField("format", "json");
        $sample->setField("sign_type", "RSA");
        $ret = $sample->execute();//向融360发送请求
        //echo 'reCompleteOrderInfo';
        var_dump($ret);
        //$ret_res = json_decode($ret,true);//解析融360返回数据

        if($ret['error']==200){
            //重推成功
        }else{
            //重推失败
        }
    }
    /***********融360|（绑定银行卡）发送短信|（机构提供）| ******************
     * @AUTH-TYS
     * @param order_no
     * @return
     *
     */
    public  function verifyRongBankSms(){
        try{
            $postArray=$this->jsonToArray(); //将融360请求数据-转换成数组
            $order_no =  $postArray['biz_data']['order_no'];//业务数据
            $appIds=$this->getAppIdsByOrder($order_no);
            $verify_code=$postArray['biz_data']['verify_code'];
            $postArray['biz_data']['user_mobile']=13269706193;
            $type=1;//银行卡绑定|type为1
            $sentVerifyCode = SendSMS::getVerifyCode($postArray['biz_data']['user_mobile'],$type);//验证码匹配
            //var_dump($verify_code);
            //var_dump($sentVerifyCode);
            if($verify_code!=$sentVerifyCode){
                $this->ajaxReturn(['code' =>400, 'msg' => '验证码输入错误']);
            }
            //验证码输入正确|实际帮卡|
            //跨模块调用pay控制器下|绑定新的银行卡【隐患：融360用户绑定信用卡失败的问题】
            A('Home/Pay')->bindVerifySmsRong(trim($appIds['customer_id']),$postArray['biz_data']['user_name'],$postArray['biz_data']['bank_card'],$postArray['biz_data']['user_mobile'],$postArray['biz_data']['open_bank'],$postArray['biz_data']['id_number']);
            //绑定银行卡成功后--结果通知融360|同步异步的问题
            //$this->returnBindBankReslut(1);//绑卡成功时调用||失败时：$this->returnBindBankReslut(2)
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' =>204, 'msg' => $e->getMessage()]);
        }
        // Response::format($ret);
    }
    /***********融360|绑卡接口（机构提供）|方式2 验证码绑卡******************
     * @AUTH-TYS
     * @param order_no
     * @return
     *
     */
    public  function bindBankListRong(){
        try{
            $postArray=$this->jsonToArray(); //将融360请求数据-转换成数组
            $order_no =  $postArray['biz_data']['order_no'];//业务数据
            $appIds=$this->getAppIdsByOrder($order_no);
            if(!$appIds){
                $this->ajaxReturn(['code'=>201,'msg'=>'订单号错误']);//订单号错误|
            }
            $appIds['customer_id']='366237';
            /**********bind_card_src:1=>用户绑定新卡 2=>选择已有的旧卡**********/
            if($postArray['biz_data']['bind_card_src']==1){//用户绑定新卡|
                /*$real_name = M('Customer')->field('id,real_name')->where(['id'=>trim($appIds['customer_id'])])->find();
                if($real_name!=$postArray['biz_data']['user_name']){//校验持卡人是否本人
                    $this->ajaxReturn(['code'=>202,'msg'=>'持卡人非本人']);//持卡人非本人--禁止绑定
                }*/
                $cardNum = M('CustomerBankInfo')->field('id,customer_id')->where(['customer_id'=>trim($appIds['customer_id'])])->select();
                if(count($cardNum)>2){//先校验银行卡数量
                    $this->ajaxReturn(['code'=>203,'msg'=>'用户最多可以绑定两张银行卡']);//用户最多可以绑定两张银行卡
                }
                /**********绑卡|验证码校验*********/
                $data_arr=[];
                $postArray['biz_data']['user_mobile']=13269706193;
                $type=1;//银行卡绑定|type为1
                $ret = SendSMS::verifyCode($postArray['biz_data']['user_mobile'], $type);//发送验证
                if($ret){
                    $data_arr['bind_status']=0;
                    $this->ajaxReturn(['code'=>200,'msg'=>'success','data'=>$data_arr ]);
                }else{
                    $this->ajaxReturn(['code'=>400,'msg'=>'验证码发送失败']);
                }
            }else if($postArray['biz_data']['bind_card_src']==2){//用户选择已有旧卡
                A('Home/Pay')->changeRongMainCard($appIds['customer_id'],$postArray['biz_data']['bank_card']);
            }

        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' =>204, 'msg' => $e->getMessage()]);
        }
       // Response::format($ret);
    }
    /***********融360|（获取用户绑定银行卡结果）| ******************
     * @AUTH-TYS
     * @param $reslut_int|绑卡结果：1成功 2失败
     * @return
     */
    public  function returnBindBankReslut($reslut_int){
        try{
            $arr_ = [];//业务数据-数组
            $arr_['order_no'] = '245132241561415';
            $arr_['bind_status'] = $reslut_int;
            $arr_['reason'] ='';
            $sample = new OpenapiClient();
            $sample->setMethod('is.api.v3.order.bindcardfeedback');
            $sample->setField("version", "1.0");
            $sample->setField("biz_data",json_encode($arr_));//设置业务参数|数据
            $sample->setField("format", "json");
            $sample->setField("sign_type", "RSA");
            $ret = $sample->execute();//向融360发送请求
            //echo 'reCompleteOrderInfo';
            var_dump($ret);
            //$ret_res = json_decode($ret,true);//解析融360返回数据
            if($ret['error']==200){
                //绑卡结果推送成功
            }else{
                //绑卡结果推送成功
            }
        } catch (BusinessException $e) {
            //$this->ajaxReturn(['code' =>204, 'msg' => $e->getMessage()]);
        }
        // Response::format($ret);
    }
    /***********融360|卡列表接口（机构提供）|******************
     * @AUTH-TYS
     * @param order_no
     * @return
     *  
     */
    public  function getbankListRong(){
        try{
            $postArray=$this->jsonToArray(); //将融360请求数据-转换成数组
            $order_no =  $postArray['biz_data']['order_no'];//业务数据
            $appIds=$this->getAppIdsByOrder($order_no);
            $appIds['customer_id']='366237';
            $ret = D('CustomerBankInfo')->getList($appIds['customer_id']);
            //var_dump($order_no);
            //var_dump($ret);
            if($ret){
                $data=[];
                $data['order_no']=$order_no;
                $data['code']=200;
                $data['msg']='success';
                $data['data']['bank_card_list']='"'.json_encode($ret).'"';
                $this->ajaxReturn($data);
            }else{
                $data=[];
                $data['order_no']=$order_no;
                $data['code']=400;
                $data['msg']='failed';
                //$data['data']['bank_card_list']='"'.json_encode($ret).'"';
                $this->ajaxReturn($data);
            }

        } catch (BusinessException $e) {
            $ret = ['code' =>201, 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn(['code'=>200]);
    }
    /******融360|审批结果拉取接口（机构提供）|单期|金额范围|期限范围|********
     * @AUTH-TYS
     * @param order_no
     * @return
     */
    public  function getLoanApprovalReslut(){
        try{
            $postArray=$this->jsonToArray(); //将融360请求数据-转换成数组
            $order_no =  $postArray['biz_data']['order_no'];//业务数据
            $appIds=$this->getAppIdsByOrder($order_no);
            $appIds['customer_id']='186541';//关联找钱花的用户id
            $appIds['order_no']='801217';//关联找钱花的订单id
            $test=M('ConsumeHistory')->where(['customer_id'=>$appIds['customer_id'],'id'=>$appIds['order_no']])->order('id DESC')->find();
            if(!$test){
                $this->ajaxReturn(['code'=>201,'msg'=>'订单不存在！']);
            }
            $order_status=$test['type'].'-'.$test['status'];//根据订单状态--查询审核通过与否
            $order_arr=['4-5'=>'failed','4-6'=>'failed','4-7'=>'failed','4-8'=>'failed', '4-11'=>'failed',
                        '4-12'=>'success',
                        '5-1'=>'failed','5-3'=>'failed','5-8'=>'failed'];//拒绝的数组
            //var_dump($order_arr[$order_status]);
            $res = A('Home/UserCenter')->getWithdrawalsRongRecord($appIds['customer_id'],0,1);//获取提现账单|提现信息|账单
            //var_dump($res['data'][0]['amount']);
            //$days=M('SysInstallmentPlan')->getProductDays();
            if($order_arr[$order_status]=='success'){//审核通过
                $access_data=[];
                $access_data['order_no']=$order_no;
                $access_data['conclusion']=10;
                $access_data['amount_type']=1;//1=金额范围（如500-1000元）；默认为1
                $access_data['max_loan_amount']="2000.0000";//保留小数点后4位,单位元；
                $access_data['min_loan_amount']="500.0000";//保留小数点后4位,单位元；
                $access_data['loan_term_option']= $this->getProductDays(); ;
                $access_data['approval_time']=time();//反馈订单审批通过的时间戳,10位数字
                $access_data['pay_amount']=$res['data'][0]['amount'];//1. 用户的总还款额（包括本金利息管理费手续费等一切费用）；2. 保留小数点后4位；
                $access_data['receive_amount']=$res['data'][0]['apply_amount'];//1. 实际打款到银行卡的金额2. 保留小数点后4位，单位元；
                $access_data['term_type']="1";//1=多个期限（如7天、14天等);；默认为1
                $access_data['term_unit']="1";//1=单期产品（按天计息），默认为1
                $access_data['range_amount']="100";//表示在最大审批金额和最小审批金额间的最小变更金额；例如，审批金额最大值为200，审批金额最小值为100，金额变更粒度为50，则表示审批范围值为：100,150,200。
                $access_data['remark']="审核数据：".json_encode($access_data)."";//备注（例如：信用评分过低#拒绝客户，如果没备注，信用评分过低#）
                $this->ajaxReturn(['code'=>200,'msg'=>'success','data'=>$access_data]);
            }elseif($order_arr[$order_status]=='failed'){//审核拒绝
                $deny_data=[];
                $deny_data['order_no']=$order_no;
                $deny_data['conclusion']=40;
                $deny_data['remark']=$order_status;
                $deny_data['refuse_time']=time();
                $this->ajaxReturn(['code'=>200,'msg'=>'success','data'=>$deny_data]);
            }else{//其他情况
                $this->ajaxReturn(['code'=>400,'msg'=>'success','data'=>$order_arr[$order_status]]);
            }
            //$this->ajaxReturn($data);
            //var_dump($test);
            //var_dump($postArray);
        } catch (BusinessException $e) {
            $ret = ['code' =>201, 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn(['code'=>200]);
    }
    /******融360|批确认结果推送接口（机构提供）|单期|金额范围|期限范围|********
     *
     * @AUTH-TYS
     * @param 贷款信息（贷款金额和期限）
     * 用户确认申请的贷款信息==>融360将调用
     * @return 是否客户接收成功
     *{
    "sign": "xxxxxxxxxxxxxxxxxxxxxx",
    "biz_data":"{
    "order_no":"245132241561415",
    "loan_amount":"1000.00",
    "loan_term":"12"
    }"
    }
     * {
    "code": 200,
    "msg": "",
    "data":{}
    }
     * {
    "code": 400,
    "msg": "您请求的参数有误"
    }
     */
    public  function cofirmUserLoan(){
        try{
            $postArray=$this->jsonToArray(); //将融360请求数据-转换成数组
            $order_no =  $postArray['biz_data']['order_no'];//业务数据
            $appIds=$this->getAppIdsByOrder($order_no);
            $appIds['customer_id']='186541';//关联找钱花的用户id
            $appIds['order_no']='801217';//关联找钱花的订单id
            //var_dump($postArray['biz_data']);
            //var_dump($postArray['biz_data']['loan_amount']);//金额
            //var_dump($postArray['biz_data']['loan_term']);//借款期限
            if(!$appIds){//校验订单有效性
                //订单不存在||该return等会直接放在在getAppIdsByOrder里
                $this->ajaxReturn(['code'=>201,'msg'=>'订单不存在！']);
            }
            /******该笔提现订单校验|金额|是否有正在提现订单******/
            $rongConsume=M('ConsumeHistory')->field('id,customer_id,type,status,amount,consume_amount,
                        repay_id,pass_time')->has($appIds['order_no']); //校验订单状态金额|
            $rongUser=M('Customer')->field('id,mobile,cash_amount,balance_prepaid,id_num,real_name')->has($appIds['customer_id']); //用户金额校验
            $verifyStr = 'consume_amount-'.($postArray['biz_data']['loan_amount']*100).'-type-4-status-12-cash_amount-'.($postArray['biz_data']['loan_amount']*100).'-balance_prepaid-0';
            $postStr   = 'consume_amount-'.$rongConsume['consume_amount'].'-type-'.$rongConsume['type'].'-status-'.$rongConsume['status'].'-cash_amount-'.$rongUser['cash_amount'].'-balance_prepaid-'.$rongUser['balance_prepaid'];
            if($verifyStr!=$postStr){//校验订单|用户|金额|
                //$this->ajaxReturn(['code'=>202,'msg'=>'参数不准确！']);
            }
            /***********用户提现**************/
            $postArray['biz_data']['loan_amount']=1;
            //$listBank=D('CustomerBankInfo')->getListRong($appIds['customer_id']);
            $model = 'WithdrawalsOrder/withdrawalsOrder';
            $xml_data = [
                'customer_id' => '366237',
                'consume_id' => '',
                'money' => '',
                'repay_id' => '1',
                'amount' => $postArray['biz_data']['loan_amount'],
                'rongResource' => '1'
            ];
            $test=D('Ajax')->ajaxPost($model, $xml_data);
            var_dump($test);
            $test=json_decode($test);
            var_dump($test);
            var_dump($test->code);
        } catch (BusinessException $e) {
            $ret = ['code' =>201, 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        //$this->ajaxReturn(['code'=>200]);
    }
/***找钱花对外（如：Rong360）提供的对外接口|
 * @判断用户是否可以申请找钱花产品|
 * @判断用户是否可以走复贷简化流程
 * @AUTH-TYS
 * @param 手机号|身份证|姓名
 * @return 该用户是否可以申请找钱花产品
 * @return code=400:不可申请 code=400&reason=c001（进行中的贷款）|reason=c002（不良贷款记录）|reason=c003(X天内被机构审批拒绝过)
 * @return code=200:可申请
 * @return 是否可走复贷简化流程
 * @return code=200&is_reloan=0:正常流程 code=200&is_reloan=0:复贷用户
 * 复贷return:OrderInfo&ApplyDetail
 * 正常return:OrderInfo&ApplyDetail&addInfo
 * 请求地址：/Home/Rong/checkUserReLoan
 */
    public  function checkUserReLoan(){
        try{    //echo  strtoupper(md5('13552163323'.strtoupper('422326199204042554'))).PHP_EOL;die;
                $postArray=$this->jsonToArray(); //将融360请求数据-转换成数组
                $data =  $postArray['biz_data'];//业务数据
                Log::rong_write_borrow('---Rong/check_ReLoan|融360复贷检查用户：'.$data['user_name'].'|---');
                $check_user_md5=D('Customer')->checkRongUser($data['user_name']);//根据用户名|返回md5签名数组集
                if(!array_key_exists($data['md5'],$check_user_md5)){/***校验（手机号+身份证）md5|***///成功返回用户信息数组strtoupper(md5($mobile.strtoupper($idcard))).PHP_EOL;
                    Log::rong_write_borrow('---Rong/check_ReLoan|融360-|复贷检查失败|--用户：'.trim($check_user_md5[trim($data['md5'])]['id']).$data['user_name'].'|md5:'.$data['md5'].'-----');
                    $this->ajaxReturn(['code'=>201,'msg'=>'用户不存在']);
                }
                /***检查用户是否可以申请产品***/
                $reloan_data = M('ConsumeHistory')->field('id,customer_id,type,status')->where(['customer_id'=>trim($check_user_md5[trim($data['md5'])]['id'])])->order('id DESC')->find();
                $ck_str=$reloan_data['type'].'-'.$reloan_data['status'];//用户当前状态
                $deny_arr_all=['4-5','4-12','5-1','5-8']; /***不可申请用户状态***/
                $deny_arr_all_reson=['4-5'=>'c001','4-12'=>'c001','5-1'=>'c001','5-8'=>'c001'];
                if(in_array($ck_str,$deny_arr_all)){
                    Log::rong_write_borrow('-----Rong/check_ReLoan|融360-|复贷检查|不可申请--用户：'.trim($check_user_md5[trim($data['md5'])]['id']).$data['user_name'].'|md5:'.$data['md5'].'|用户状态：'.$ck_str.'-----');
                    $this->ajaxReturn(['code'=>400,'msg'=>'不可申请','reason'=>$deny_arr_all_reson[$ck_str]]);
                }
                /***30天拒绝用户群体***/
                if($ck_str=='4-6'){//人工拒绝|30天//4-6|人工拒绝|（30天）    4-7|决策      4-11系统自动拒绝
                    //客户id trim($check_user_md5[trim($md5)]['id'])
                    $vet_data=M('CreditVetting')->field('id,customer_id,consume_id,add_time,status')->where(['customer_id'=>trim($check_user_md5[trim($data['md5'])]['id']),'consume_id'=>$reloan_data['id']])->find();
                    if(!$vet_data){
                        Log::rong_write_borrow('-----Rong/check_ReLoan|融360-|复贷检查|不可申请--用户：'.trim($check_user_md5[trim($data['md5'])]['id']).$data['user_name'].'|md5:'.$data['md5'].'|人工拒绝出现错误-----');
                        $this->ajaxReturn(['code'=>201,'msg'=>'人工拒绝出现错误']);
                    }
                    if(time()-strtotime($vet_data['add_time'])<30*24*60*60){
                        Log::rong_write_borrow('-----Rong/check_ReLoan|融360-|复贷检查|不可申请--用户：'.trim($check_user_md5[trim($data['md5'])]['id']).$data['user_name'].'|md5:'.$data['md5'].'|c003-----');
                        $this->ajaxReturn(['code'=>400,'msg'=>'不可申请','reason'=>'c003']);

                    }
                }
                /***检查用户是否可以走富贷简化流程***/
                $customerAuth=D('CustomerAuth')->getCustomerAuthInfo($check_user_md5[trim($data['md5'])]);
                //Log::rong_write_borrow('---Rong/check_ReLoan|融360复贷检查用户：认证信息：'.json_encode($customerAuth).'|---');
                if($customerAuth['credit_step']<2||$customerAuth['sesame_score']<0||$customerAuth['china_mobile']<0){// credit_step:1`基本资料* credit_step:2`身份证认证* credit_step:3`活体认证* $customerAuth['credit_step'];//$customerAuth['sesame_score'];芝麻//$customerAuth['china_mobile'];运营商
                   //***认证不全|用户走正常请款流程||融360暂时不走活体认证
                    $normal_data=[];
                    $normal_data['approval_amount']=2000;//可申请的最大金额
                    $normal_data['approval_term']=D('SysInstallmentPlan')->getProductDays();//可申请的产品期限
                    $normal_data['term_unit']=1;//产品期限单位
                    $normal_data['is_reloan']=0;//是否复贷简化留程
                    Log::rong_write_borrow('---Rong/check_ReLoan|融360复贷检查用户：'.trim($check_user_md5[trim($data['md5'])]['id']).$data['user_name'].json_encode($customerAuth).'|走正常流程---');
                    $this->ajaxReturn(['code'=>200,'msg'=>'正常流程贷款客户：','data'=>$normal_data]);

                }else{ //***复贷用户|走简化流程
                    $bank=D('CustomerBankInfo')->getDefaultList($check_user_md5[trim($data['md5'])]['id']); //*************************获取用户绑定的默认的银行卡 //echo  '用户id：'.trim($check_user_md5[trim($md5)]['id']); //var_dump($check_user_md5[trim($md5)]);
                    if(!$bank[0]||($bank[0]['card_user_name']!=$data['user_name'])){//校验持卡人是否本人
                        Log::rong_write_borrow('---Rong/check_ReLoan|融360复贷检查用户：'.trim($check_user_md5[trim($data['md5'])]['id']).$data['user_name'].json_encode($bank).'|持卡人非本人---');
                        $this->ajaxReturn(['code'=>400,'msg'=>'持卡人必须是本人','data'=>['user_name'=>$data['user_name'],'card_user_name'=>$bank['card_user_name']]]);
                    }
                    $normal_data=[];
                    $normal_data['bank_address']='';//用户开户行
                    $normal_data['user_mobile']=$check_user_md5[trim($data['md5'])]['mobile'];
                    $normal_data['user_name']=$check_user_md5[trim($data['md5'])]['real_name'];
                    $normal_data['bank_card']=$bank[0]['card_num'];
                    $normal_data['open_bank']=$bank[0]['gate_id'];
                    $normal_data['is_reloan']=1;//复贷简化流程标识
                    $normal_data['term_unit']= 1;//产品期限单位
                    $normal_data['approval_amount']=2000;//申请最大的金额
                    $normal_data['approval_term']=D('SysInstallmentPlan')->getProductDays();//可申请的产品期限
                    Log::rong_write_borrow('---Rong/check_ReLoan|融360复贷检查用户：'.trim($check_user_md5[trim($data['md5'])]['id']).$data['user_name'].json_encode($customerAuth).'|走复贷流程---');
                    $this->ajaxReturn(['code'=>200,'msg'=>'复贷客户简化流程','data'=>$normal_data]);

                }
        } catch (BusinessException $e) {
            $ret = ['code' =>201, 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn(['code'=>200,'msg','data'=>[]]);
    }
    /***找钱花对外(融360)提供的接口|
     * @接收第三方平台推送来的订单|用户信息
     * @param---orderInfo订单的基本信息
     * @param---applyDetail申请人填写的基本信息
     * @param---addInfo抓取信息等订单的基本信息
     * 校验机构用户|身份信息校验|信用等级校验|注册机构用户|
     * 生成找钱花对应申请记录|4-12
     * @AUTH-TYS
     * @return code=200成功|
     * @return code!=200失败|
     */
    public  function orderPush(){
        try{
            $strPost = file_get_contents('php://input');  //抓取数据
            $strPostArr=json_decode($strPost,true);
            $postArray=$this->jsonToArray_($strPostArr['biz_data']); //将融360请求数据-转换成数组
            $postData=json_decode($postArray,true);//订单信息$postData['orderInfo']|用户信息$postData['applyDetail']|抓取信息$postData['addInfo']
            /***注册用户|***///姓名：$postData['applyDetail']['bureau_user_name'];//手机号码：$postData['applyDetail']['phone_number_house'];//身份证号码：$postData['applyDetail']['user_id'];//用户其他信息：json_encode($postData['applyDetail']);
            $user_exists=M('Customer')->field('id')->where(['mobile'=>trim($postData['applyDetail']['phone_number_house'])])->find();
            if($user_exists){
                Log::rong_write_borrow("***手机号：".trim($postData['applyDetail']['phone_number_house'])."：已存在".json_encode($user_exists)."*****：");
                $this->ajaxReturn(['code'=>201,'msg'=>'用户已存在']);
            }
            /***新用户信用认证校验|注意此处是聚合认证***/
            $res = D("Customer")->getAddressById($postData['applyDetail']['user_id']); //认证身份证相关信息
            if($res){//用户资格预筛选(现开启百融+威震认证)
                $verify_data = [
                    //'id' => $customerId,
                    'real_name' => $postData['applyDetail']['bureau_user_name'],
                    'id_num' => $postData['applyDetail']['user_id'],
                    'gender' => $res['sex'],
                    'birthday' => $res['birthday'],
                    'birthplace' => $res['area'],
                    'mobile' => $postData['applyDetail']['phone_number_house']
                ];
            }
            $hook = BaseHook::executeHook("DECISION_ENGINE_HOOK", $verify_data, Constant::DECISION_ENGINE_HOOK);
            Log::rong_write_borrow("***手机号：".trim($postData['applyDetail']['phone_number_house'])."黑名单认证|百融认证结果：".json_encode($hook)."*****：");
            if (Constant::SUCCESS != $hook['code']) {
                $res_data['qualified'] = 0; //用户不合格，不可以下单
                $res_data['reason'] = $hook['msg'];
                Log::rong_write_borrow("***手机号：".trim($postData['applyDetail']['phone_number_house'])."黑名单认证|百融认证结果：".json_encode($hook)."*****：");
                $this->ajaxReturn(['code'=>201,'msg'=>'百融黑名单用户，认证不通过']);
            }else{
                $res_data['qualified'] = 1;
            }
            $weizhen = A('Home/Blacklist'); /************身份证验证-威震************/
            $data_sql = [];
            $data_sql['idCard'] =$postData['applyDetail']['phone_number_house'];
            $weizhen_data = $weizhen->ckweizhen($postData['applyDetail']['bureau_user_name'],$postData['applyDetail']['user_id'],$postData['applyDetail']['phone_number_house']);
            Log::rong_write_borrow("***手机号".trim($postData['applyDetail']['phone_number_house'])."黑名单认证|威震认证结果：".json_encode($weizhen_data)."*****：");
            Log::rong_write_borrow("***手机号".trim($postData['applyDetail']['phone_number_house'])."黑名单认证|威震认证结果：是否在黑名单：".$weizhen_data['black_result']."|黑名单等级：".$weizhen_data['risk_level']."|*****：");

            if($weizhen_data['black_result']=='Y'&&$weizhen_data['risk_level']=='高'){
                Log::rong_write_borrow("***手机号".trim($postData['applyDetail']['phone_number_house'])."进入威震黑名单认证|*****：");
                $res_data['qualified'] = 0; //用户不合格，不可以下单
                $res_data['reason'] = Constant::IN_BLACK_LIST_9F;
                $weizhen->addDataBase($data_sql);
                $this->ajaxReturn(['code'=>202,'msg'=>'威震黑名单用户，认证不通过']);
            }
            Log::rong_write_borrow("***手机号".$postData['applyDetail']['bureau_user_name']."黑名单认证|威震认证未命中*****：");
            /***认证通过|注册机构用户|***/
            $postData['applyDetail'];
            $register_data=[];
            $register_data['real_name'] = $postData['applyDetail']['bureau_user_name'];
            $register_data['mobile'] = $postData['applyDetail']['phone_number_house'];
            $register_data['id_num'] = $postData['applyDetail']['user_id'];
            $register_data['gender'] = $res['sex'];
            $register_data['gender'] = $res['sex'];
            $register_data['birthday'] = $res['birthday'];
            $register_data['birthplace'] = $res['area'];
            $register_data['birthplace']=$postData['addInfo']['zhima']['ali_trust_score']['score'];
            $user_id = M('Customer')->add($register_data);//注册机构用户|入库|
            $orderinfoData = json_encode($postData['orderInfo']);//保存订单额外订单信息
            $applyDetailData=json_encode($postData['applyDetail']);//保存额外用户信息
            $addInfo =json_encode($postData['addInfo']);//保存抓取信息
            //联系人格式|请确认/****手机|联系人|添加|***/
            $postData['addInfo']['mobile']['user']['contact_phone'];//mobile.user.contact_phone
            $user_contract_data=[];
            $contract_data=[];
            $contract_data['customer_id']=$user_id;
            $contract_data['contact_name']=$postData['addInfo']['mobile']['user']['contact_phone'];
            $user_contract_data[]=$contract_data;
            M('CustomerContact')->add($user_contract_data);
            /***添加用户认证信息***/
            $user_id=447758;
            $auth_data=[];
            $auth_data['customer_id']=$user_id;
            $auth_data['id_num']=1;
            $auth_data['face_pass']=1; //注意：活体认证
            $auth_data['china_mobile']=1;
            $auth_data['jd_pass']=1;
            $auth_data['ali_pass']=1;
            $user_auth_id=M('CustomerAuth')->add($auth_data);//入库|
            /***注册机构用户成功|添加新用户申请记录|***/
            //产品列表
            $products_id=[];
            //$products_id['7']='';
            $products_id['14']='2';
            $products_id['30']='3';
            $products_id['21']='4';
            $products_id['28']='5';
            //print_r($postData['orderInfo']);
            $order=A('Home/WithdrawalsOrder');
            $apply_data=[];
            $apply_data['customer_id']=$user_id;
            //暂时没用起来
            $apply_data['province']='';//
            $apply_data['country']='';//
            $apply_data['apply_amount']=$postData['orderInfo']['application_amount'];//申请金额
            $apply_data['repay_id']=$products_id[$postData['orderInfo']['application_term']];//申请的产品
            $apply_data['push_id']='';
            $apply_data['black_box']='';
            //注意这个数组
            $apply_data['customer']='';
            $apply_data['customer']['tongdun_device_id']='';
            //return  生成申请记录|4|12
            $applyorder=$order->withdrawalsRongApply($apply_data);
            /***关联|订单号|用户id|***/
            //M('关联表')
            //M('关联表')
            if($applyorder['code']==''){
                //$this->ajaxReturn(['code' =>200, 'msg' => '成功']);
            }else{
                //$this->ajaxReturn($ret = ['code' =>201, 'msg' => '生成申请失败了！']);
            }
            /*********************************融360审核通过|生成51订单|关联融360订单和系统订单号*********************************/
        } catch (BusinessException $e) {
            $ret = ['code' =>201, 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        //$this->ajaxReturn(['code'=>200]);
        //var_dump($postData['addInfo']['mobile']);mobile.user.contact_phone
        //var_dump($postData['addInfo']['mobile']['tel']);
    }
    /*************重推补充信息接口(融360提供)**********
     *---融360异步请求补充信息推送接口
     * @param
     * @return
     */
    public  function reCompleteOrderInfo(){
        $arr_ = [];//业务数据-数组
        $arr_['order_no'] = '245132241561415';
        $arr_['timer'] = '28';
        $sample = new OpenapiClient();
        $sample->setMethod('is.api.v3.order.notifypushaddinfo');
        $sample->setField("version", "1.0");
        $sample->setField("biz_data",json_encode($arr_));//设置业务参数|数据
        $sample->setField("format", "json");
        $sample->setField("sign_type", "RSA");
        $ret = $sample->execute();//向融360发送请求
        //echo 'reCompleteOrderInfo';
        var_dump($ret);
        //$ret_res = json_decode($ret,true);//解析融360返回数据

        if($ret['error']==200){
            //重推成功
        }else{
            //重推失败
        }
    }
    public  function check_ReLoan_(){
        //将融360请求数据-转换成数组
        $postArray=$this->jsonToArray();
        //业务数据
        //$data =  $postArray['biz_data'];

        /*******************************校验md5|start|************************************/
       var_dump($postArray);
      // $test=json_decode($strPost,true);
        //var_dump($test);
        // $this->ajaxReturn(['code'=>200]);
    }
/*****************************融360|rong_zhao接口|start************************************/
    public function getContractUrl($contract_page = 0, $contract_pos = 0){
        $contract_url = array(
            //借款合同
            '0' => array('0' => self::apiUrl.'/Home/Protocol/borrowProtocol' ), //00默认为0展示借款合同
            '3' => array('1' => self::apiUrl.'/Home/Protocol/borrowProtocol' ), //3:审批结果页
            '5' => array('1' => self::apiUrl.'/Home/Protocol/borrowProtocol' ), //5:账单页面
            //续借合同
            '6' => array('1' => self::apiUrl."/Home/Protocol/order" ), //6:续借合同
        );
        return $contract_url[$contract_page][$contract_pos];
    }
    public function pull_contract(){//合同拉取接口（机构提供）
        Log::write('********************************PullContractStart*********************************', Log::DEBUG);
        //$postArray = $this->jsonToArray();
        $strPost = file_get_contents('php://input');
        $datastre=$strPost;
        $postArray = json_decode($strPost,true);
        $data =  $postArray['biz_data'];
        $data=$this->jsonToArray_($data);
        $data=json_decode($data,true);
        //$sign = $postArray['sign'];
        //$data =  $postArray['biz_data'];
        Log::write('ContractRequest='.json_encode($data), Log::DEBUG);
        $order_no = $data['order_no'];//订单编号
        //$order_no = '250519545817409';//这里模拟接收到order_no

        // $res = D('ConsumeHistory')->field("customer_id, amount")->where("order_no = '$order_no' ")->find();
        $res = $this->getAppIdsByOrder($order_no);
        $consume_id = $res['order_no'];
        $customerId = $res['customer_id'];
        $res1 = D('ConsumeHistory')->field("amount")->where("id = '$consume_id' and customer_id = '$customerId' ")->find();
        Log::write('sql1='.D('ConsumeHistory')->getLastSql(), Log::DEBUG);
        $amount = $res1['amount'];
        $customer_id = $res['customer_id'];
        // var_dump($amount);die;


        $user_id = $data['user_id'];//用户ID
        $contract_return_url = $data['contract_return_url'];//合同接口url

        //目前只有场景1

        //根据page、pos返回对应的响应
        try {
            D('Customer')->has($customer_id);
            $ret = ['code' => 200, 'msg' => 'success'];


            // if (isset($data['contract_page']) && !empty($data['contract_pos'])) {
            $contract_page = $data['contract_page'];//合同所属的页面
            $contract_pos = $data['contract_pos'];//合同在页面内的顺序展示
            // $contract_page = 5;//这里先默认两个值
            // $contract_pos = 1;

            if (in_array($contract_page, [3,5,6])) {
                $contract_url = $this->getContractUrl($contract_page, $contract_pos);
            } else {
                $contract_url = $this->getContractUrl(0, 0);//默认借款合同
            }

            $contract_url = $contract_url . "/customer_id/" . $customer_id . "/amount/" . $amount;
            Log::write('$contract_url ='. $contract_url, Log::DEBUG);
            // }



            $ret['data']['contract_url'] = $contract_url;

        } catch (BusinessException $e) {
            $ret = ['code' => 400, 'msg' => $e->getMessage()];
        }
        Log::write('ContractResponse='.json_encode($ret), Log::DEBUG);
        // Response::format($ret);
        // $this->ajaxReturn($ret);
        // echo "<pre>";
        Log::write('********************************PullContractEnd*********************************', Log::DEBUG);
        echo json_encode($ret);die;
        // var_dump($ret);die;

        $this->ajaxReturn($ret);

    }
    public function push_order_status($customerId,$orderNo){//订单状态反馈接口
        $order_no = M('ThirdpartyConsumeHistory')->where("customer_id = '$customerId' and third_order_no = '$orderNo' ")->find();
        Log::rong_write_borrow('|实际放款后|订单状态反馈接口|push_order_status|$customerId:'.$customerId.'|$orderNo:'.$orderNo);
        $consume_id_=$order_no['consume_id']?$order_no['consume_id']:$order_no['order_no'];

        $data = D('ConsumeHistory')->field("status, type,repayment_time, update_time")->where("customer_id = '$customerId' and id =".$consume_id_)->find();
        $data['order_no'] = $order_no['third_order_no'];//这里将通过关联表查到的第三方订单附到这里
        $repayment_time = $data['repayment_time'];
        /***组装响应信息***/
        $ret['biz_data']['order_no'] = $data['order_no'];
        //$order_status = $data['status'];
        /*if ($order_status == 12) {//12提现人工审核通过
            $order_status = 100;//审批通过的状态
        } elseif ($order_status == 6 || $order_status == 11) {//6审核未通过11自动拒绝
            $order_status = 110;//审批未通过
        } elseif ($order_status == 9) {//9:订单已取消
            $order_status = 161;//贷款取消
        } elseif ($order_status == 13) {//13提现失败
            $order_status = 169;//放款失败
        } elseif ($order_status == 1) {//1:订单已完成
            $order_status = 170;//放款成功
        } elseif (time() > $repayment_time) {//当前时间大于最后还款时间
            $order_status = 180;//逾期
        } elseif ($order_status == 3) {//3:已还款
            $order_status = 200;//已还款
        }*/
        $order_type = $data['type'];
        //$order_status = $data['status'];
        $str=$order_type.'-'.$data['status'];//var_dump($str);die;
        if ($str == '4-12') {//12提现人工审核通过
            $order_status = 100;//审批通过的状态
        } elseif ($str == '4-6' || $str == '4-11') {//6审核未通过11自动拒绝
            $order_status = 110;//审批未通过
        } elseif ($str == '5-9'||$str == '4-9') {//9:订单已取消
            $order_status = 161;//贷款取消
        } elseif ($str == '5-13') {//13提现失败
            $order_status = 169;//放款失败
        } elseif ($str == '5-1') {//1:订单已完成
            $order_status = 170;//放款成功
        } elseif (time() > $repayment_time&&$str=='5-1') {//当前时间大于最后还款时间
            $order_status = 180;//逾期
        } elseif ($str == '5-3') {//3:已还款
            $order_status = 200;//已还款
        }
        $ret['biz_data']['order_status'] = $order_status;
        if ($order_status < 100) {//若机构状态不在附录中，该字段为空
            $ret['biz_data']['order_status'] = "";
        }
        $update_time = $data['update_time'];
        $ret['biz_data']['update_time'] = $update_time;
        Log::rong_write_borrow('PushOrderStatusRequestBizData='.json_encode($ret['biz_data']));
        $sample= new OpenapiClient();
        $sample->setField("order_no",$data['order_no']);//合作机构唯一标识
        $sample->setField("order_status",$order_status);//合作机构唯一标识
        $sample->setField("update_time",$data['update_time']);//合作机构唯一标识
        $sample->setMethod('is.api.v3.order.orderfeedback');
        $ret= $sample->execute();
        Log::rong_write_borrow('+++|订单状态反馈接口:融360返回结果：'.json_encode($ret).'|***');
    }
    public function pull_order_status(){//拉取订单状态接口
        Log::rong_write_borrow('**************************PullOrderStatusResponse_Start**************************', Log::DEBUG);
        $strPost = file_get_contents('php://input');
        $datastre=$strPost;
        $postArray = json_decode($strPost,true);
        $data =  $postArray['biz_data'];
        $data=$this->jsonToArray_($data);
        $data=json_decode($data,true);
        Log::rong_write_borrow('拉取订单状态接口：数据流：'.$datastre);
        $order_no = $data['order_no'];
        try {
            $res = $this->getAppIdsByOrder($order_no);
            $consume_id = $res['consume_id']>0?$res['consume_id']:$res['order_no'];
            $customerId = $res['customer_id'];
            $data = D('ConsumeHistory')->field("customer_id, id, type,status, repayment_time, update_time")->where("id = '$consume_id' and customer_id = '$customerId' ")->find();
            //Log::rong_write_borrow('sql1='.D('ConsumeHistory')->getLastSql());
            $repayment_time = $data['repayment_time'];
            /****组装响应信息***/
            $ret = ['code' => 200, 'msg' => 'success'];
            $ret['data']['order_no'] = $order_no;
            $order_type = $data['type'];
            $order_status = $data['status'];
            $str=$order_type.'-'.$order_status['status'];//var_dump($str);die;
            if ($str == '4-12') {//12提现人工审核通过
                $order_status = 100;//审批通过的状态
            } elseif ($str == '4-6' || $str == '4-11') {//6审核未通过11自动拒绝
                $order_status = 110;//审批未通过
            } elseif ($str == '5-9'||$str == '4-9') {//9:订单已取消
                $order_status = 161;//贷款取消
            } elseif ($str == '5-13') {//13提现失败
                $order_status = 169;//放款失败
            } elseif ($str == '5-1') {//1:订单已完成
                $order_status = 170;//放款成功
            } elseif (time() > $repayment_time&&$str=='5-1') {//当前时间大于最后还款时间
                $order_status = 180;//逾期
            } elseif ($str == '5-3') {//3:已还款
                $order_status = 200;//已还款
            }
            $ret['data']['order_status'] = $order_status;
            if ($order_status < 100) {//若机构状态不在附录中，该字段为空
                $ret['data']['order_status'] = "";
            }
            $update_time = $data['update_time'];
            $ret['data']['update_time'] = $update_time;
            Log::rong_write_borrow('***拉取订单状态接口|pull_order_status返回数据：'.json_encode($ret['data']));
        } catch (BusinessException $e) {
            $ret = ['code' => 400, 'msg' => $e->getMessage()];
            Log::rong_write_borrow('PullOrderStatusResponse='.json_encode($ret));
        }
        Log::rong_write_borrow('**************************PullOrderStatusResponse_End**************************'.json_encode($ret));
        $this->ajaxReturn($ret);
    }
    public function push_repayment_plan($customerId,$orderNo){
        $order_no = M('ThirdpartyConsumeHistory')->where("customer_id = '$customerId' and third_order_no = '$orderNo' ")->find();
        Log::rong_write_borrow('|实际放款后|订单状态反馈接口|push_order_status|$customerId:'.$customerId.'|$orderNo:'.$orderNo);
        $consume_id=$order_no['consume_id']?$order_no['consume_id']:$order_no['order_no'];
        //这是请求融360接口，将还款计划推送给他们，然后他们那边更新信息，获取响应
        Log::rong_write_borrow('还款计划推送|push_repayment_plan');
        $ret['biz_data'] = D('CustomerBankInfo')->field("card_num as bank_card, gate_id as open_bank")->where(array("is_default"=>1,"customer_id"=>$customerId))->find();

        $ret['biz_data']['bank_card'] = $ret['biz_data']['bank_card'];
        //biz_data.open_bank
        $ret['biz_data']['open_bank'] = D('MerchantBankInfo')->getBankName($ret['biz_data']['open_bank']);

        /************获取用户默认银行卡信息*结束**********************/
        //biz_data.order_no
        $order_no = M('ThirdpartyConsumeHistory')->field("third_order_no")->where("customer_id = '$customerId' and consume_id = '$consume_id' ")->find();
        $ret['biz_data']['order_no'] = $order_no['third_order_no'];
        // var_dump($ret['biz_data']);die;

        //biz_data.repayment_plan
        {
            //0.参数检查
            if(!$customerId || !$consume_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $data = $getMsg = D('ConsumeHistory')->getCashBillByBillId($consume_id);
            // var_dump($data);die;
            Log::write('sql1='.D('ConsumeHistory')->getLastSql(), Log::DEBUG);
            // Log::write("取现账单数据：".count($data), Log::INFO);
            // period_no
            $period_no = 1;////////////////////////////////////目前是账单不分期，默认只有一期
            $ret['biz_data']['repayment_plan']['0']['period_no'] = $period_no;
            // due_time 到期时间
            $due_time = strtotime($data['list']['0']['repay_date'])+86399;///////////////////////这里保留86399看他们到底要什么样的时间戳
            $ret['biz_data']['repayment_plan']['0']['due_time'] = $due_time;
            // var_dump($ret);die;
            // amount还款总金额
            $amount = $data['list']['0']['repay_amount'];//单位 分
            $amount = (float)$amount/100;
            $ret['biz_data']['repayment_plan']['0']['amount'] = $amount;
            // paid_amount已还款金额 空
            $paid_amount = "";
            $ret['biz_data']['repayment_plan']['0']['paid_amount'] = $paid_amount;
            //bill_status转换
            if ($data['list']['0']['state'] == 2) {//$data['list']['0']['state']还款状态0已还1逾期2未还
                $bill_status = 1;//未到期
            } elseif ($data['list']['0']['state'] == 0) {
                $bill_status = 2;//以还
            } elseif ($data['list']['0']['state'] == 1) {
                $bill_status = 3;//逾期
            }
            $ret['biz_data']['repayment_plan']['0']['bill_status'] = $bill_status;
            //pay_type还款方式
            $pay_type = 1;//默认主动还款1
            if ($bill_status == 2) {
                $CustomerBillPayLog = M('CustomerBillPayLog');
                $CustomerBillPayLogInfo = $CustomerBillPayLog->field('pay_action, pay_time')->where(['customer_id' => $customerId,'consume_id' => $consume_id,'status' => 1])->find();//1手动还款 2系统代扣
                Log::write('sql2='.M('CustomerBillPayLog')->getLastSql(), Log::DEBUG);
                //pay_type
                $pay_type = $CustomerBillPayLogInfo['pay_action'];//pay_action 1手动还款 2系统代扣
                if ($pay_type == 2) {
                    $pay_type = 4;//转成融360对应的状态 银行代扣
                }
                //还款成功才有success_time
                //success_time
                $success_time = $CustomerBillPayLogInfo['pay_time'];
                $ret['biz_data']['repayment_plan']['0']['success_time'] = (int)$success_time;
            }
            $ret['biz_data']['repayment_plan']['0']['pay_type'] = (int)$pay_type;
            //can_repay_time可以还款时间
            $can_repay_time = $data['consume_time'];
            $can_repay_time = strtotime($can_repay_time);
            $ret['biz_data']['repayment_plan']['0']['can_repay_time'] = $can_repay_time;
            //remark
            if ($bill_status == 1) {//1未到期
                $remark = "产品未到期，按合同应还" . $ret['biz_data']['repayment_plan']['0']['amount'];
            } elseif ($bill_status == 2) {//2以还
                $remark = "产品已还，按合同已还" . $ret['biz_data']['repayment_plan']['0']['amount'];
            } elseif ($bill_status == 3) {//3逾期
                $remark = "逾期应还" . $data['list']['0']['repay_amount'] . ",本金" . $data['amount'] . "违约金" . $data['list']['0']['over_date_fee'] . "罚息" . $data['list']['0']['late_fee'];
            }
            $ret['biz_data']['repayment_plan']['0']['remark'] = $remark;
            //is_able_defer
            $is_able_defer = 1;//初始化默认可以展期
            $timer = $data['timer'];

            $can_repay_time1 = strtotime(date("Y-m-d",$can_repay_time));
            $can_repay_time1 = date("Y-m-d", $can_repay_time1);

            $one_term_time = strtotime($can_repay_time1 . "+".$timer." day");

            {
                $res = D('ConsumeInstallmentHistory')->field("update_time, status")->where("parent_id = '$consume_id'")->find();
                Log::write('sql3='.D('ConsumeInstallmentHistory')->getLastSql(), Log::DEBUG);
                $update_time = $res['update_time'];//已经展期的不为0
                $status = $res['status'];//0未还1已还
                Log::write('$res='.json_decode($res), Log::DEBUG);
            }

            if (time() > $one_term_time || $update_time > 0 ) {
                Log::write('---------------------$is_able_defer_in---------------------', Log::DEBUG);
                $is_able_defer = 0;//逾期超过一个账单周期，不支持展期//展期过的单子不支持展期
                Log::write('---------------------$is_able_defer_over---------------------', Log::DEBUG);
            }
            $ret['biz_data']['repayment_plan']['0']['is_able_defer'] = $is_able_defer;
            // echo "<pre>";
            // var_dump($ret);die;

            // $ret['data']['repayment_plan'] = count($data)?$data['data']:[];
        }


        $repayment=[];
        $over_fee=100;
        $over_fee_=10;
        //$arr1['open_bank']=$ret['biz_data']['open_bank'];;
        $arr1['period_no']=$ret['biz_data']['repayment_plan']['0']['period_no'];
        $arr1['due_time']=$ret['biz_data']['repayment_plan']['0']['due_time'];
        $arr1['amount']=$ret['biz_data']['repayment_plan']['0']['amount'];
        $arr1['paid_amount']=$ret['biz_data']['repayment_plan']['0']['paid_amount'];
        //$arr1['pay_type']=$ret['biz_data']['repayment_plan']['0']['pay_type'];
        $arr1['pay_type']=5;
        $arr1['bill_status']=$ret['biz_data']['repayment_plan']['0']['bill_status'];
        $arr1['can_repay_time']=$ret['biz_data']['repayment_plan']['0']['can_repay_time'];
        $arr1['remark']=$remark;
        //$arr1['is_able_defer']=$ret['biz_data']['repayment_plan']['0']['is_able_defer'];//暂时不支持战棋
        $arr1['is_able_defer']=0;//暂时不支持战棋
        $repayment[]=$arr1;
        // var_dump($repayment);die;
        $sample= new OpenapiClient();
        $sample->setField("order_no", $ret['biz_data']['order_no']);//
        $sample->setMethod('is.api.v3.order.pushrepayment');
        $sample->setField("open_bank",$ret['biz_data']['open_bank']);
        $sample->setField("bank_card",$ret['biz_data']['bank_card']);
        $sample->setField("repayment_plan",$repayment);
        //$sample->setField("version", "1.0");
        //$sample->setField("format", "json");
        $ret = $sample->execute();
        Log::rong_write_borrow('还款计划推送|push_repayment_plan|结果：'.json_encode($ret));
        $this->ajaxReturn($ret);

        //响应数据示例{"error": 200,"msg": "success","is_api_v3_order_pushrepayment_responese": []}
    }
    public function pull_repayment_plan(){//还款计划拉取
        $strPost = file_get_contents('php://input');
        $postArray = json_decode($strPost,true);
        $data_ = $this->jsonToArray_($postArray['biz_data']);
        $data_=json_decode($data_,true);
        $order_no = $data_['order_no'];
        //查银行卡信息
        try {
            //这是请求融360接口，将还款计划推送给他们，然后他们那边更新信息，获取响应
            Log::rong_write_borrow('还款计划拉取|pull_repayment_plan');
            Log::write('***getAppIdsByOrderStart***', Log::DEBUG);
            $res = $this->getAppIdsByOrder($order_no);
            $consume_id = $res['consume_id'];//找到对应的订单号
            $customerId = $res['customer_id'];
            Log::write('***************************getAppIdsByOrderEnd***************************', Log::DEBUG);
            /***获取用户默认银行卡信息*开始***/
            $ret['biz_data'] = D('CustomerBankInfo')->field("card_num as bank_card, gate_id as open_bank")->where(array("is_default"=>1,"customer_id"=>$customerId))->find();
            $ret['biz_data']['open_bank'] = D('MerchantBankInfo')->getBankName($ret['biz_data']['open_bank']);
            $ret['biz_data']['order_no'] = $order_no;
            /***获取用户默认银行卡信息*结束***/
            if(!$customerId || !$consume_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $data = $getMsg = D('ConsumeHistory')->getCashBillByBillId($consume_id);
            Log::write('sql2='.D('ConsumeHistory')->getLastSql(), Log::DEBUG);
            $period_no = 1;
            $ret['biz_data']['repayment_plan']['0']['period_no'] = $period_no;
            $due_time = strtotime($data['list']['0']['repay_date'])+86399;///////////////////////这里保留86399看他们到底要什么样的时间戳
            $ret['biz_data']['repayment_plan']['0']['due_time'] = $due_time;
            // amount还款总金额
            $amount = $data['list']['0']['repay_amount'];//单位 分
            $amount = (float)$amount/100;
            $ret['biz_data']['repayment_plan']['0']['amount'] = $amount;
            // paid_amount已还款金额 空
            $paid_amount = "";
            $ret['biz_data']['repayment_plan']['0']['paid_amount'] = $paid_amount;
            //bill_status转换
            if ($data['list']['0']['state'] == 2) {//$data['list']['0']['state']还款状态0已还1逾期2未还
                $bill_status = 1;//未到期
            } elseif ($data['list']['0']['state'] == 0) {
                $bill_status = 2;//以还
            } elseif ($data['list']['0']['state'] == 1) {
                $bill_status = 3;//逾期
            }
            $ret['biz_data']['repayment_plan']['0']['bill_status'] = $bill_status;
            //pay_type还款方式
            $pay_type = 1;//默认主动还款1
            if ($bill_status == 2) {
                $CustomerBillPayLog = M('CustomerBillPayLog');
                $CustomerBillPayLogInfo = $CustomerBillPayLog->field('pay_action, pay_time')->where(['customer_id' => $customerId,'consume_id' => $consume_id,'status' => 1])->find();//1手动还款 2系统代扣
                Log::write('sql3='.M('CustomerBillPayLog')->getLastSql(), Log::DEBUG);
                //pay_type
                $pay_type = $CustomerBillPayLogInfo['pay_action'];//pay_action 1手动还款 2系统代扣
                if ($pay_type == 2) {
                    $pay_type = 4;//转成融360对应的状态 银行代扣
                }
                //还款成功才有success_time
                //success_time
                $success_time = $CustomerBillPayLogInfo['pay_time'];
                $ret['biz_data']['repayment_plan']['0']['success_time'] = (int)$success_time;
            }
            $ret['biz_data']['repayment_plan']['0']['pay_type'] = (int)$pay_type;
            //can_repay_time可以还款时间
            $can_repay_time = $data['consume_time'];
            $can_repay_time = strtotime($can_repay_time);
            $ret['biz_data']['repayment_plan']['0']['can_repay_time'] = $can_repay_time;
            //remark
            if ($bill_status == 1) {//1未到期
                $remark = "产品未到期，按合同应还" . $ret['biz_data']['repayment_plan']['0']['amount'];
            } elseif ($bill_status == 2) {//2以还
                $remark = "产品已还，按合同已还" . $ret['biz_data']['repayment_plan']['0']['amount'];
            } elseif ($bill_status == 3) {//3逾期
                $remark = "逾期应还" . $data['list']['0']['repay_amount'] . ",本金" . $data['amount'] . "违约金" . $data['list']['0']['over_date_fee'] . "罚息" . $data['list']['0']['late_fee'];
            }
            $ret['biz_data']['repayment_plan']['0']['remark'] = $remark;
            $is_able_defer = 1;//初始化默认可以展期
            $timer=$data['timer'];
            $can_repay_time1 = strtotime(date("Y-m-d",$can_repay_time));
            $can_repay_time1 = date("Y-m-d", $can_repay_time1);
            $one_term_time = strtotime($can_repay_time1 . "+".$timer." day");
            {
                $res = D('ConsumeInstallmentHistory')->field("update_time, status")->where("parent_id = '$consume_id'")->find();
                Log::write('sql4='.D('ConsumeInstallmentHistory')->getLastSql(), Log::DEBUG);
                $update_time = $res['update_time'];//已经展期的不为0
                $status = $res['status'];//0未还1已还
                Log::write('$res='.json_decode($res), Log::DEBUG);
            }
            // echo $update_time;die;
            if (time() > $one_term_time || $update_time > 0 ) {
                Log::write('---------------------$is_able_defer_in---------------------', Log::DEBUG);
                $is_able_defer = 0;//逾期超过一个账单周期，不支持展期//展期过的单子不支持展期
                Log::write('---------------------$is_able_defer_over---------------------', Log::DEBUG);
            }
            $ret['biz_data']['repayment_plan']['0']['is_able_defer'] = $is_able_defer;
            $biz_data['order_no']= $ret['biz_data']['order_no'];
            $biz_data['open_bank']=$ret['biz_data']['open_bank'];
            $biz_data['bank_card']=$ret['biz_data']['bank_card'];
            $data1['period_no']=$ret['biz_data']['repayment_plan']['0']['period_no'];
            $data1['due_time']=$ret['biz_data']['repayment_plan']['0']['due_time'];
            $data1['amount']=$ret['biz_data']['repayment_plan']['0']['amount'];
            $data1['paid_amount']=$ret['biz_data']['repayment_plan']['0']['paid_amount'];
            //$data1['pay_type']=$ret['biz_data']['repayment_plan']['0']['pay_type'];
            $data1['pay_type']=5;
            $data1['bill_status']=$ret['biz_data']['repayment_plan']['0']['bill_status'];
            $data1['can_repay_time']=$ret['biz_data']['repayment_plan']['0']['can_repay_time'];
            $data1['remark']=$remark;
            //$data1['is_able_defer']=$ret['biz_data']['repayment_plan']['0']['is_able_defer'];//暂时不支持战棋
            $data1['is_able_defer']=0;//暂时不支持战棋
            $biz_data['repayment_plan'][]=$data1;
            Log::rong_write_borrow('还款计划推送|push_repayment_plan|结果：'.json_encode($ret));
            $this->ajaxReturn(['code'=>200,'msg'=>'success','data'=>$biz_data]);

        } catch (BusinessException $e) {
            $ret = ['code' => 400, 'msg' => $e->getMessage()];
        }
        // Response::format($ret);
        // $this->ajaxReturn($ret);
        // echo "<pre>";
        //echo json_encode($ret);die;
        // var_dump($ret);die;
        $this->ajaxReturn($ret);
    }
/*****************************融360|rong_zhao接口|end************************************/


    /****** 待审核订单刷新 ******/
    public function orderRefresh(){
        try{
            $customerId = I('post.customer_id');
            $consumeId = I('post.consume_id');
            if(!$customerId || !$consumeId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            D('Customer')->has($customerId);
            //获取用户当前订单的状态
            $res = M('ConsumeHistory')->alias('h')
                ->join('left join merchant m on h.merchant_id = m.id')
                ->field('h.*, m.name as merchant_name')
                ->where(['h.id'=>$consumeId])->find();
            Log::write('data='.json_encode($res), Log::DEBUG);
            Log::write('sql='.M('ConsumeHistory')->getLastSql(), Log::DEBUG);
            $res['consume_id'] = $res['id'];
            $res['repay_type'] = $res['type'];
            $data = D('ConsumeHistory')->getCurOrderStatus($res);
            Log::write('data='.json_encode($data), Log::DEBUG);
            $order_step = [];

            $new_id = sprintf('%010s', $res['id']);
            $data['order_id'] = date('ymd', $res['add_time']) . $new_id;
            $data['merchant_name'] = $data['merchant_name'] ? $data['merchant_name'] : $res['merchant_name'];
            $data['add_time'] = $data['add_time'] ? $data['add_time'] : date('Y-m-d H:i:s', $res['add_time']);
            $data['amount'] = $data['amount'] ? $data['amount'] : $res['amount'];
            //业务员拒绝客户端进行虚拟成功展示
            Log::write($data['status'], Log::DEBUG);
            if(($data['status'] == ConsumeHistoryModel::STATUS_REVIEW_FAILED) && (time()) - $res['add_time'] < 5*60) {
                //第2步：贷前照片待上传（市场初审待审核）
                $where = [
                    'consume_id' => $res['id'],
                    'status' => ['in',
                        CreditVettingModel::STATUS_WAITING_REVIEW.",".
                        CreditVettingModel::STATUS_MARKET_REFUSE
                    ]
                ];
                //获取各步骤的时间 2
                $credit_data = M('CreditVetting')->where($where)->select();
                Log::write('jujue='.M('CreditVetting')->getLastSql(), Log::DEBUG);
                if(count($credit_data) >= 2){
                    $order_step = Constant::$step;
                    foreach ($order_step as $k => $v) {
                        $order_step[$k]['date_time'] = date('Y-m-d H:i:s', time());
                    }

                    $data['cur_step'] = 2;
                    $data['err_code'] = 2;
                    $data['status'] = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
                    $data['discount'] = $res['discount_interest'] == 2 ? 1 : 0;
                    $new_id = sprintf('%010s', $res['id']);
                    $data['order_id'] = date('ymd', $res['add_time']) . $new_id;

                    foreach ($credit_data as $k=>$value){
                        if ($value['status'] == CreditVettingModel::STATUS_WAITING_REVIEW){
                            $order_step[0]['date_time'] = $value['add_time'];
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_REFUSE){
                            $order_step[1]['date_time'] = $value['add_time'];
                            $order_step[1]['display'] = '审核照片已由业务员代表辅助上传成功';
                        }
                    }
                    $data['step'] = $order_step;
                    $data['status'] = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
                }
            } elseif ($data['status'] == ConsumeHistoryModel::STATUS_WAIT_REVIEWED) {
                $order_step = Constant::$step;
                foreach ($order_step as $k => $v) {
                    $order_step[$k]['date_time'] = date('Y-m-d H:i:s', time());
                }

                $data['cur_step'] = 0;
                $data['err_code'] = 0;
                $data['discount'] = $res['discount_interest'] == 2 ? 1 : 0;

                //审批状态 1:信审部通过 2:待审核 3:信审部拒绝 4:决策拒绝 5:自动审核通过 6:市场部通过 7:市场部强烈通过 8:市场部拒绝 9:业务员担保 10:信审初审不合格 11:信审初审合格 12:信审复审不合格 13:市场复审通过
                if ($res['status'] == ConsumeHistoryModel::STATUS_WAIT_REVIEWED) {
                    //第2步：贷前照片待上传（市场初审待审核）
                    $data['cur_step'] = 1;
                    //获取各步骤的时间 2
                    $where = [
                        'consume_id' => $res['id'],
                        'status' => CreditVettingModel::STATUS_WAITING_REVIEW
                    ];
                    $credit_data = M('CreditVetting')->where($where)->find();
                    $order_step[0]['date_time'] = $credit_data['add_time'];
                } elseif ($res['status'] == ConsumeHistoryModel::STATUS_WAIT_TWO) {
                    //第3步：贷前照片待审核（信审初审待审核）
                    $data['cur_step'] = 2;
                    //获取各步骤的时间 2,6||7
                    $where = [
                        'consume_id' => $res['id'],
                        'status' => ['in',
                            CreditVettingModel::STATUS_WAITING_REVIEW.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWED.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWEDER
                        ]
                    ];
                    $credit_data = M('CreditVetting')->where($where)->select();
                    Log::write('sql='.M('CreditVetting')->getLastSql(), Log::DEBUG);
                    foreach ($credit_data as $k=>$value){
                        if ($value['status'] == CreditVettingModel::STATUS_WAITING_REVIEW){
                            $order_step[0]['date_time'] = $value['add_time'];
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWED || $value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWEDER){
                            $order_step[1]['date_time'] = $value['add_time'];
                            $order_step[1]['display'] = '审核照片已由业务员代表辅助上传成功';
                        }
                    }
                } elseif ($res['status'] == ConsumeHistoryModel::STATUS_REVIEW_CANCEL) {
                    //第3步：贷前照片待审核（市场重新上传照片，信审初审待审核）
                    $data['cur_step'] = 2;
                    //获取各步骤的时间 2,6||7,10,14
                    $where = [
                        'consume_id' => $res['id'],
                        'status' => ['in',
                            CreditVettingModel::STATUS_WAITING_REVIEW.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWED.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWEDER.",".
                            CreditVettingModel::STATUS_MANUAL_FIRST_NOPASS.",".
                            CreditVettingModel::STATUS_MANUAL_CREDIT_ERR
                        ]
                    ];
                    $credit_data = M('CreditVetting')->where($where)->select();
                    foreach ($credit_data as $k=>$value){
                        if ($value['status'] == CreditVettingModel::STATUS_WAITING_REVIEW){
                            $order_step[0]['date_time'] = $value['add_time'];
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWED || $value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWEDER){
                            $order_step[1]['date_time'] = $value['add_time'];
                            $order_step[1]['display'] = '审核照片已由业务员代表辅助上传成功';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MANUAL_FIRST_NOPASS){
                            $order_step[2]['date_time'] = $value['add_time'];
                            $order_step[2]['display'] = '图片资料不合格，请业务代表用小工具辅助重新提交';
                            $data['err_code'] = 3;
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MANUAL_CREDIT_ERR){
                            $order_step[2]['date_time'] = $value['add_time'];
                            $order_step[2]['display'] = '运营商信息没有收到，请业务代表辅助用链接重新认证';
                            $data['err_code'] = 1;
                        }
                    }
                } elseif ($res['status'] == ConsumeHistoryModel::STATUS_SEND_GOODS) {
                    //第4步：发货照片待上传（市场复审待审核）
                    $data['cur_step'] = 3;
                    //获取各步骤的时间 2,6||7,11
                    $where = [
                        'consume_id' => $res['id'],
                        'status' => ['in',
                            CreditVettingModel::STATUS_WAITING_REVIEW.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWED.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWEDER.",".
                            CreditVettingModel::STATUS_MANUAL_FIRST_PASS
                        ]
                    ];
                    $credit_data = M('CreditVetting')->where($where)->select();
                    foreach ($credit_data as $k=>$value){
                        if ($value['status'] == CreditVettingModel::STATUS_WAITING_REVIEW){
                            $order_step[0]['date_time'] = $value['add_time'];
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWED || $value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWEDER){
                            $order_step[1]['date_time'] = $value['add_time'];
                            $order_step[1]['display'] = '审核照片已由业务员代表辅助上传成功';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MANUAL_FIRST_PASS){
                            $order_step[2]['date_time'] = $value['add_time'];
                            $order_step[2]['display'] = '您的申请信审审核已通过';
                        }
                    }
                } elseif ($res['status'] == ConsumeHistoryModel::STATUS_SEND_MONEY_WAITING) {
                    //第5步：等待放款（信审复审待审核）
                    $data['cur_step'] = 4;
                    //获取各步骤的时间 2,6||7,11,13
                    $where = [
                        'consume_id' => $res['id'],
                        'status' => ['in',
                            CreditVettingModel::STATUS_WAITING_REVIEW.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWED.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWEDER.",".
                            CreditVettingModel::STATUS_MANUAL_FIRST_PASS.",".
                            CreditVettingModel::STATUS_MARKET_NEXT_PASS
                        ]
                    ];
                    $credit_data = M('CreditVetting')->where($where)->select();
                    foreach ($credit_data as $k=>$value){
                        if ($value['status'] == CreditVettingModel::STATUS_WAITING_REVIEW){
                            $order_step[0]['date_time'] = $value['add_time'];
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWED || $value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWEDER){
                            $order_step[1]['date_time'] = $value['add_time'];
                            $order_step[1]['display'] = '审核照片已由业务员代表辅助上传成功';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MANUAL_FIRST_PASS){
                            $order_step[2]['date_time'] = $value['add_time'];
                            $order_step[2]['display'] = '您的申请信审审核已通过';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_NEXT_PASS){
                            $order_step[3]['date_time'] = $value['add_time'];
                            $order_step[3]['display'] = '您的提货单已上传成功';
                        }
                    }
                } elseif ($res['status'] == ConsumeHistoryModel::STATUS_SEND_MONEY_FAILED) {
                    //第5步：等待放款（市场重新上传照片，信审复审待审核）
                    $data['cur_step'] = 4;
                    //获取各步骤的时间 2,6||7,11,12
                    $where = [
                        'consume_id' => $res['id'],
                        'status' => ['in',
                            CreditVettingModel::STATUS_WAITING_REVIEW.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWED.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWEDER.",".
                            CreditVettingModel::STATUS_MANUAL_FIRST_PASS.",".
                            CreditVettingModel::STATUS_MANUAL_NEXT_NOPASS
                        ]
                    ];
                    $credit_data = M('CreditVetting')->where($where)->select();
                    foreach ($credit_data as $k=>$value){
                        if ($value['status'] == CreditVettingModel::STATUS_WAITING_REVIEW){
                            $order_step[0]['date_time'] = $value['add_time'];
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWED || $value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWEDER){
                            $order_step[1]['date_time'] = $value['add_time'];
                            $order_step[1]['display'] = '审核照片已由业务员代表辅助上传成功';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MANUAL_FIRST_PASS){
                            $order_step[2]['date_time'] = $value['add_time'];
                            $order_step[2]['display'] = '您的申请信审审核已通过';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_NEXT_PASS){
                            $order_step[3]['date_time'] = $value['add_time'];
                            $order_step[3]['display'] = '您的提货单已上传成功';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MANUAL_NEXT_NOPASS){
                            $order_step[4]['date_time'] = $value['add_time'];
                            $order_step[4]['display'] = '提货单上传信息有误，请改正后重新上传';
                            $data['err_code'] = 3;
                        }
                    }
                } else {
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
                $data['step'] = $order_step;
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $data;
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    /*************************融360补充信息start**************************************/
    public function informationPush(){
        try{
            $strPost = file_get_contents('php://input');  //抓取数据
            Log::rong_write_borrow('---Rong/orderPush|订单基本信息推送|数据：'.$strPost);
            $strPostArr=json_decode($strPost,true);
            $data=json_decode($strPostArr['biz_data'],true);//订单信息$postData['orderInfo']|用户信息$postData['applyDetail']|抓取信息$postData['addInfo']
            $datas=json_decode($data['device_info_all'],true);//订单信息$postData['orderInfo']|用户信息$postData['applyDetail']|抓取信息$postData['addInfo']
            if($data<>''){
                $order_no=$data['order_no'];    //第三方订单
                $order_nos=$this->getAppIdsByOrder($order_no);//根据第三方订单--影视对应的着钱花ids
                $customer_id=$order_nos['customer_id'];
                if($order_nos<>''){
                    /***customer表身份证信息添加start***/
                    $data_=array(
                        'real_name'=>$data["Name_OCR"],
                        'gender'=>$data["ID_Sex_OCR"],
                        'nation'=>$data["ID_Ethnic_OCR"],
                        'birthplace'=>$data["ID_Address_OCR"],
                        'id_num'=>$data["ID_Number_OCR]"],
                        'sign_organ'=>$data["ID_Issue_Org_OCR"],
                        'valid_period'=>$data["ID_Due_time_OCR"],
                    );
                    $test=M('Customer')->where(['id'=>$customer_id])->save($data_);
                    Log::rong_write_borrow("---------融360补充信息|用户身份证信息添加数据".json_encode($data_)."|添加结果".$test."---------：");
                    /***customer表身份证信息添加end***/
                    /***联系人信息添加start***/
                    $sql_data=array(
                        "customer_id"=>$customer_id,
                        "wechat"=>$data["sns_weixin"],
                        "qq_num"=>$data["sns_qq"],
                        "user_address"=>$data["addr_detail"],
                        "company_name"=>$data["company_name"],
                        "company_phone"=>$data["company_number"],
                        "company_address"=>$data["company_addr_detail"],
                        "brothers_name"=>$data["emergency_contact_personA_name"],
                        "brothers_phone"=>$data["emergency_contact_personA_phone"],
                        "friends_name"=>$data["emergency_contact_personB_name"],
                        "friends_phone"=>$data["emergency_contact_personB_phone"],
                        "add_time"=>date('Y-m-d H:i:s', time())
                    );
                    $res = M('CustomerExtraInfo')->add($sql_data);//用户联系人添加
                    Log::rong_write_borrow("---------融360补充信息|CustomerExtraInfo|用户联系人添加数据".json_encode($sql_data)."---------：");
                    Log::rong_write_borrow("---------融360补充信息|CustomerExtraInfo|用户联系人添加结果".M('CustomerExtraInfo')->getLastSql()."---------：");
                    if($res === false){
                        BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                    }
                    $auth = M('CustomerAuth')->where(['customer_id'=>$customer_id])->find();
                    if(!$auth){
                        $auth_data['customer_id'] = $customer_id;
                        $res = M('CustomerAuth')->add($auth_data);
                        Log::rong_write_borrow("---------融360补充信息|CustomerAuth|添加数据".json_encode($auth_data)."|结果：".json_encode($res)."---------：");
                        if($res === false){
                            Log::rong_write_borrow("---------融360补充信息|CustomerAuth|添加数据失败".json_encode($auth_data)."---------：");
                            BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                        }
                    }
                    /***身份验证信息添加***/
                    $id_num_url=[
                        'customer_id'=>$customer_id,
                        'photo_url'=>$data["ID_Positive"][0],//身份证正面照
                        'type'=>20,
                        'add_time'=>time()
                    ];
                    $id_nums_url=[
                        'customer_id'=>$customer_id,
                        'photo_url'=>$data["ID_Negative"][0],//身份证反面照
                        'type'=>21,
                        'add_time'=>time()
                    ];
                    M("thirdparty_upload_file",null)->add($id_num_url);//身份证正面照
                    Log::rong_write_borrow("---------融360补充信息|用户身份证正面添加数据".json_encode($data["ID_Positive"][0])."|---------：");
                    Log::rong_write_borrow("---------融360补充信息|用户身份证正面添加结果".M("thirdparty_upload_file",null)->getLastSql()."---------：");
                    M("thirdparty_upload_file",null)->add($id_nums_url);//身份证反面照
                    Log::rong_write_borrow("---------融360补充信息|用户身份证反面添加数据".json_encode($data["ID_Negative"][0])."|---------：");
                    Log::rong_write_borrow("---------融360补充信息|用户身份证反面添加结果".M("thirdparty_upload_file",null)->getLastSql()."---------：");
                    /*******用户活体添加******/
                    foreach($data["photo_assay"] as $k=>$v){
                        $photo_[]=array(
                            'customer_id'=>$customer_id,
                            'photo_url'=>$v,//身份证反面照
                            'type'=>25,
                            'add_time'=>time()
                        );
                    }
                    $test1=M("thirdparty_upload_file",null)->addAll($photo_);//活体检测
                    Log::rong_write_borrow("---------融360补充信息|用户活体接收数据".json_encode($data["photo_assay"])."|结果：".$test1."|添加数据：".json_encode($photo_)."|".M("thirdparty_upload_file",null)->getLastSql()."---------：");
                    /***用户手机通讯录添加***/
                    $contact_phonelist=$data["contacts"]["phone_list"];
                    $contactModel = M("CustomerContact");
                    foreach($contact_phonelist as $key=>$val){
                        unset($val["uid"]);
                        $map[]=array(
                            'customer_id'=>$customer_id,
                            'contact_phone'=>$val['phone'],
                            'contact_name'=>$val["name"],
                            'group'=>'',
                            'nick'=>'',
                            'memo'=>'',
                        );
//
                    }
                    $contactModelSql=$contactModel->addAll($map);
                    Log::rong_write_borrow("---------融360补充信息|用户手机通讯录接收".json_encode($contact_phonelist)."|结果：".$contactModelSql."|添加数据：".json_encode($map)."|".$contactModel->getLastSql()."---------：");
                    /***用户手机通话详情添加***/
                    $contact_calllog=$data["contacts"]["call_log"];
                    foreach($contact_calllog as $ke=>$va){
                        unset($va["uid"]);
                        $maps[]=array(
                            'customer_id'=>$customer_id,
                            'type'=>$va['type'],
                            'date'=>$va["date"],
                            'duration'=>$va['duration'],
                            'phone'=>$va['phone'],
                        );
                    }
                    $callLogs=M("thirdparty_call_log",null)->addAll($maps);
                    Log::rong_write_borrow("---------融360补充信息|用户手机通话详情|".$callLogs."数据".json_encode($contact_calllog)."---------：");
                    Log::rong_write_borrow("---------用户手机通话详情添加数据".json_encode($maps)."---------：");
                    Log::rong_write_borrow("---------用户手机通话详情录添加结果".M("thirdparty_call_log",null)->getLastSql()."---------：");
                    /****************用户手机通话详情添加end***********/
                    /****************用户手机信息添加start***********/
                    $data_=[];
                    $data_["customer_id"] = $customer_id;
                    $data_["app_name"]=$data["app_name"];
                    $data_["app_version"]=$data["app_version"];
                    $data_["channel"]=$data["channel"];
                    $data_["device_num"]=$data["contacts"]["device_num"];
                    $data_["device_info"]=$data["contacts"]["device_info"];
                    $data_["installed_apps"]=$data["contacts"]["installed_apps"];
                    $data_["installed_apps_version"]=$data["contacts"]["installed_apps_version"];
                    $data_["app_location"]=$data["contacts"]["app_location"];
                    $data_["is_simulator"]=$data["is_simulator"];
                    $data_["platform"]=$datas["platform"];
                    $data_["tele_num"]=$datas["tele_num"];
                    $data_["tele_name"]=$datas["tele_name"];
                    $data_["imei"]=$datas["imei"];
                    $data_["imsi"]=$datas["imsi"];
                    $data_["seria_no"]=$datas["seria_no"];
                    $data_["android_id"]=$datas["android_id"];
                    $data_["udid"]=$datas["udid"];
                    $data_["mac"]=$datas["mac"];
                    $data_["idfa"]=$datas["idfa"];
                    $data_["idfv"]=$datas["idfv"];
                    $data_["ios_plat"]=$datas["ios_plat"];
                    $data_["ios_ver"]=$datas["ios_ver"];
                    $data_["uuid"]=$datas["uuid"];
                    $data_["is_root"]=$datas["is_root"];
                    $data_["dns"]=$datas["dns"];
                    $data_["mem_size"]=$datas["mem_size"];
                    $data_["storage_size"]=$datas["storage_size"];
                    $data_["ava_storage_size"]=$datas["ava_storage_size"];
                    $data_["phone_brand"]=$datas["phone_brand"];
                    $data_["android_ver"]=$datas["android_ver"];
                    $data_["device_model"]=$datas["device_model"];
                    M("thirdparty_customer_phone",null)->add($data_);
                    Log::rong_write_borrow("---------用户手机信息添加数据".json_encode($data_)."---------：");
                    Log::rong_write_borrow("---------用户手机信息添加结果".M("thirdparty_customer_phone",null)->getLastSql()."---------：");
                    /****************用户手机信息添加end***********/
                }else{
                    $this->ajaxReturn(['code'=>201,'msg'=>'订单不存在']);
                }
            }else{
                $this->ajaxReturn(['code'=>400,'msg'=>'传输数据为空']);
            }
            $this->ajaxReturn(['code'=>200,'msg'=>'接收数据成功']);
        }catch (BusinessException $e){
            $ret = ['code' =>202, 'msg' => $e->getMessage()];
        }
        Response::format($ret);
    }
    /*************************融360补充信息end**************************************/
    /*************************融360还款或展期结果反馈start**************************************/
    public function resultPayconfirm($arr){
        $sample= new OpenapiClient();
        $sample->setField("order_no", $arr['order_no']);
        $sample->setMethod('is.api.v3.order.repayfeedback');
        $sample->setField("period_nos", "1");
        //设置业务参数|数据
        $sample->setField("repay_status",$arr['repay_status']);
        $sample->setField("success_time",$arr['repay_status']);
        $sample->setField("repay_place", $arr["repay_place"]);
        $sample->setField("remark", $arr['remark']);
        //向融360请求
        $ret= $sample->execute();
        Log::rong_write_borrow('---Rong/resultPayconfirm|融360还款或展期结果反馈start|结果：'.$ret['msg'].json_encode($ret));
        $this->ajaxReturn($ret);
    }
    /*************************融360还款或展期结果反馈end**************************************/
    /*************************融360还款详情接口start**************************************/
    public function rongBillPayconfirm(){
        try{
            $strPost = file_get_contents('php://input');  //抓取数据
            $strPostArr=json_decode($strPost,true);
            $postArray=$this->jsonToArray_($strPostArr['biz_data']); //将融360请求数据-转换成数组
            $data=json_decode($postArray,true);
//            $postArray=$this->jsonToArray();
//            $data=$postArray['biz_data'];//接收过来的数据
            if($data<>''){
                $order_id=$data["order_no"];//接收从融360传过来的订单号
//                $order_id=246532992134737;    //第三方订单
                $order_nos=$this->getAppIdsByOrder($order_id);//查询是否有这个订单
//                $customer_id=$order_nos["customer_id"];
                $consume_id=$order_nos["consume_id"];
//                $consume_id=8014230;
//                $customer_id=366242;
                if(!empty($order_nos)){
                    $datas = D('ConsumeHistory')->getCashBillByBillId($consume_id);//获取账单
                    $map=[
                        'amount'=>$datas["list"]["repay_amount"]/100,
                        'remark'=>"本金：".($datas["transfer_amount"]/100)."元，服务费：".($datas["amount"]*$datas["cut_interest"]/100)."逾期罚息：".($datas["list"]["late_fee"]/100)."元，违约金：".($datas["list"]["over_date_fee"]/100)."元",
                    ];
                    $this->ajaxReturn(['code'=>200,'msg'=>'success','data'=>$map]);//返回给融360的还款明细
                }else{
                    $this->ajaxReturn(['code'=>201,'msg'=>'该笔订单不存在']);
                }
            }else{
                $this->ajaxReturn(['code'=>400,'msg'=>'接收数据为空']);
            }
        }catch (BusinessException $e){
            $ret = ['code' =>202, 'msg' => $e->getMessage()];
        }
        Response::format($ret);
    }
    /*************************融360还款详情接口end**************************************/
    /*************************融360主动还款接口start**************************************/
    public function realPayconfirm(){
        try{
//            $postArray=$this->jsonToArray();
//            $data=$postArray['biz_data'];//接收过来的数据
            $strPost = file_get_contents('php://input');  //抓取数据
            $strPostArr=json_decode($strPost,true);
            $postArray=$this->jsonToArray_($strPostArr['biz_data']); //将融360请求数据-转换成数组
            $data=json_decode($postArray,true);
            $order_ids=$data["order_no"];//接收从融360传过来的订单号
            $order_nos=$this->getAppIdsByOrder($order_ids);//查询是否有这个订单
            $customerId=$order_nos["customer_id"];
            $consumeId=$order_nos["consume_id"];
            if(!empty($order_nos)){
                $userinfo = D('Customer')->has($customerId);//查询用户是否存在
                $CustomerBankInfo = M('CustomerBankInfo');//获取用户绑定卡的支付协议号
                /***绑定多张银行卡|finishmodel|customerbanckinfo|***/
                $data_arr = $CustomerBankInfo->where("customer_id = $customerId and sub_contract_id >0 and is_default=1")->field('sub_contract_id,card_user_name')->find();
                $subContractId = $data_arr['sub_contract_id'];
                if ($subContractId =='') {
                    $this->ajaxReturn(['code'=>202,'msg'=>'请先绑定银行卡']);
                }
                /***给用户打款操作|本人银行卡校验|***/ //持卡人姓名：$recv_user_name非系统用户本人
                Log::rong_write_borrow("*****************payConfirm用户真实姓名：".$userinfo['real_name']."|持卡人姓名：".$data_arr['card_user_name']."|*****：");
                if($userinfo['real_name']!=$data_arr['card_user_name']){
                    $this->ajaxReturn(['code'=>203,'msg'=>'持卡人必须是本人']);
                }
                /***还款处理中用户|***/
                $redis = new Redis();
                $key='处理中订单-'.$consumeId;
                if($redis->get($key)){
                    Log::rong_write_borrow('**********订单正在处理中|redis|key：'.$key);
                    BusinessException::throwException('订单正在处理中');
                }
                /***还款处理中用户|***/
                $datas = D('ConsumeHistory')->getCashBillByBillId($consumeId);//获取账单
                $amount=$datas["list"]["repay_amount"];//总还款金额
                $order_id = $this->trade_no();
                $CustomerBillPayLog = M('CustomerBillPayLog');
                $data = array(//入库
                    'order_id' => $order_id,
                    'order_type' => 1,
                    'customer_id' => $customerId,
                    'consume_id' => $consumeId,
                    'consume_data' => '',
                    'repay_date' =>'',
                    'amount' => $amount,
                    'trade_id' => '',
                    'pay_type' => 1,
                    'type' => 1,
                    'balance_amount_old' =>'',
                    'balance_cash_amount_old' =>'',
                    'overdue_amount' => '',
                    'pay_action' => 1,
                );
                if (false === ($insertId = $CustomerBillPayLog->add($data))) {
                    $this->ajaxReturn(['code'=>204,'msg'=>'支付订单创建失败']);
                }
                $result = A('Home/Pay')->unsPay($subContractId,$order_id,$amount);
//                $result = ['result_code'=>'0000','result_msg'=>'success'];
                Log::rong_write_borrow('***用户还款执行返回结果：'.json_encode($result));
                if($result) {
                    $ret_code = $result['result_code'];
                    $trade_state = $result['result_msg'];
                    if($ret_code=='0000') {
                        Log::rong_write_borrow('***查询融360用户是否实际还款：'.json_encode($result));
                        //查询是否还款成功
                        $resultstatu = A('Home/Pay')->unsPaystatu($order_id);
//                        $resultstatu =['status'=>'00','result_msg'=>'success'];
                        Log::rong_write_borrow('**********查询融360用户是否实际还款返回结果status：'.$resultstatu['status']);
                        Log::rong_write_borrow('**********查询融360用户是否实际还款返回结果：desc:'.$resultstatu['desc']);
                        Log::rong_write_borrow('**********查询融360用户是否实际还款返回结果：result_msg:'.$resultstatu['result_msg']);
                        Log::rong_write_borrow('**********查询融360用户是否实际还款返回结果status：'.$resultstatu['status']);
                        Log::rong_write_borrow('**********查询融360用户是否实际还款返回结果：desc:'.$resultstatu['desc']);
                        Log::rong_write_borrow('**********查询融360用户是否实际还款返回结果：result_msg:'.$resultstatu['result_msg']);
                        if($resultstatu['status'] == '00'){
                            Log::rong_write_borrow('**********查询融360用户'.$order_id.'是否实际还款返回结果status：00|成功');
                            //还款成功写库
                            $sqldata = array('trade_state'=>$trade_state,'ret_msg'=>'success','pay_time'=>time(),'ret_code'=>$ret_code,'status'=>2);
                            $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                            $ret = Constant::getReturn(Constant::SUCCESS);
                            $ret['data'] = array('order_id'=>$order_id,'trade_no'=>$order_id,'amount' => $amount,'pay_action' => 1,'customer_id' => $customerId,'pay_time' => date('Y-m-d H:i:s',time()));
                            //更新订单状态到已还款完成
                            M('ConsumeHistory')->where(['id'=>$consumeId])->setField(['status'=>3,'update_time'=>time()]);
                            M('Customer')->where(['id'=>$customerId])->setField(['cash_amount'=>0]);
                            M('ConsumeInstallmentHistory')->where(['parent_id'=>$consumeId,'update_time'=>0])->setField(['status'=>1,'update_time'=>time()]);
                            /****返回给融360结果通知***/
                            $rets = array('order_no'=>$order_ids,'period_nos'=>1,'repay_status' => 1,'repay_place' => 1,'success_time' => time(),'remark'=>"还款总金额:$amount");
                            Log::rong_write_borrow('***查询用户'.$order_ids.'返回给融360的还款结果'.json_encode($rets));
                            $this->resultPayconfirm($rets);
                            $this->push_order_status($customerId,$order_ids);
                            /*******************返回给融360结果通知************************/
                        }else if($resultstatu['status'] == '20'){
                            Log::rong_write_borrow('***查询用户'.$order_id.'是否实际还款返回结果status：20|余额不足');
                            $status = 3;
                            $sqldata = array('ret_msg'=>'银行卡余额不足','ret_code'=>1111,'status'=>$status);
                            $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                            /***返回给融360结果通知***/
                            $rets = array('order_no'=>$order_ids,'period_nos'=>1,'repay_status' => 2,'repay_place' => 1,'success_time' =>'','remark'=>"银行卡余额不足");
                            Log::rong_write_borrow('**********查询用户'.$order_ids.'返回给融360的还款结果'.json_encode($rets));
                            $this->resultPayconfirm($rets);
                            $this->push_order_status($customerId,$order_ids);
                        }elseif($resultstatu['status'] == '10'){
                            /***处理中订单|***/
                            $key='处理中订单-'.$consumeId;
                            $redis_res=$redis->set($key,'10');
                            Log::rong_write_borrow('**********|订单号码：'.$order_id.'|查询用户是否实际还款返回结果|存入redis结果|'.json_encode($redis_res));
                            Log::rong_write_borrow('**********|订单号码：'.$order_id.'|存入redis|key:'.$key.'|value:'. $redis_res=$redis->get($key));
                            /***处理中订单|***/
                            Log::rong_write_borrow('**********|订单号码：'.$order_id.'|查询用户是否实际还款返回结果|：还款处理中');
                        }
                    } else if($ret_code=='1111') {
                        //付款提交失败
                        $status = 3;
                        $sqldata = array('ret_msg'=>$trade_state,'ret_code'=>$ret_code,'status'=>$status);
                        $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                        /***返回给融360结果通知***/
                        $rets = array('order_no'=>$order_ids,'period_nos'=>1,'repay_status' => 2,'repay_place' => 1,'success_time' =>'','remark'=>$trade_state);
                        Log::rong_write_borrow('**********查询用户'.$order_ids.'返回给融360的还款结果'.json_encode($rets));
                        $this->resultPayconfirm($rets);
                        $this->push_order_status($customerId,$order_ids);
                    }
                }
            }else{
                $this->ajaxReturn(['code'=>201,'msg'=>'该笔订单不存在']);
            }
        }catch (BusinessException $e){
            $ret = ['code' =>400, 'msg' => $e->getMessage()];
        }
        Response::format($ret);

    }
    /*************************融360主动还款接口end**************************************/
    /*************************审批结果反馈接口start**************************************/
    public function rongVerifypass(){
        $arr_=I('post.');
        $arr=$arr_['biz_data'];
        Log::rong_write_borrow('**********审批结果反馈接口|数据:'.json_encode($arr));
        $sample= new OpenapiClient();
        $sample->setField("order_no",$arr['order_no']);//此处需要修改
        $sample->setField("conclusion", $arr['conclusion']);
        $sample->setField("approval_time", $arr['approval_time']);
        $sample->setField("amount_type", $arr['amount_type']);
        $sample->setField("approval_amount",$arr['approval_amount']);
        $sample->setField("term_unit",$arr['term_unit']);
        $sample->setField("term_type",$arr['term_type']);
        $sample->setField("approval_term", $arr['approval_term']);
        $sample->setField("pay_amount", $arr['pay_amount']);
        $sample->setField("remark", $arr['remark']);
        $sample->setField("receive_amount", $arr['receive_amount']);
        $sample->setMethod('is.api.v3.order.approvefeedback');
        $ret= $sample->execute();
        Log::rong_write_borrow('**********查询用户|返回给融360的还款结果'.json_encode($ret).'|'.$ret['msg'].'|***|'.json_encode($arr));
        if($ret["error"]==200){//反馈成功，存入redis队列
            $redis = new Redis();
            $redis->lpush('successWithdrawals',trim($arr['customer_id']).'-'.$arr['consume_id']);
        }else{//反馈失败
            $redis = new Redis();
            $redis->lpush('errorWithdrawals',trim($arr['customer_id']).'-'.$arr['consume_id']);
        }
    }
    /*************************审批结果反馈接口end**************************************/

    public function getProductDays()
    {
        $products=M('SysInstallmentPlan')->field('id,timer')->select();
        $ids=[];
        foreach($products as  $v){
            $ids[$v['id']]=$v['timer'];
        }
        return $ids;
    }
    //订单号生成
    public function trade_no() {
        list($usec, $sec) = explode(" ", microtime());
        $usec = substr(str_replace('0.', '', $usec), 0 ,4);
        $str  = rand(10,99);
        return date("ymdHis").$usec.$str;
    }


}